package cn.restcloud.example.controller.mongo;

import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import cn.restcloud.framework.core.annotation.bean.BeanConfig;
import cn.restcloud.framework.core.annotation.bean.BeanType;
import cn.restcloud.framework.core.annotation.rest.MethodType;
import cn.restcloud.framework.core.annotation.rest.Param;
import cn.restcloud.framework.core.annotation.rest.Params;
import cn.restcloud.framework.core.annotation.rest.RestConfig;
import cn.restcloud.framework.core.base.IBasePageBean;
import cn.restcloud.framework.core.container.BeanFactory;
import cn.restcloud.framework.core.util.db.mongo.MongoUtil;
import cn.restcloud.framework.view.base.DocAndView;
import cn.restcloud.framework.view.util.ViewUtil;

@BeanConfig(appId = "example",beanId = "MongoUtilPageDemo",beanName = "Mongo分页查询示例",beanType = BeanType.CONTROLLER,autowired = false,singleton = true,hotMode = true)
public class MongoUtilPageDemo {

	@RestConfig(configName = "MonogoDB分页查询",method = MethodType.GET,url = "/example/mongo/listbypage")
	@Params({
		@Param(id = "pageNo", name = "当前页",defaultValue="1")
	})
	public DocAndView listByPage(int pageNo) throws Exception{
        MongoClient client=MongoUtil.getMongoClient("default"); //链接数据源mongo在平台首页的数据源中建立
		String dbName="RC_ESBLog"; //数据库名
		String tableName="P_ESBProcessNodeInstance"; //集合名称
		int pageSize=15; //每页显示数
		
		//查询条件,也可以用json创建也是可以的 org.bson.BsonDocument.parse("{'$match':{'accessDate':{$gt:'"+startDayStr+"'}}}")
		Bson filters=Filters.eq("resultCode",1);
		
		//先算出总文档数
    	int totalRecords=MongoUtil.getCount(dbName, tableName, filters);
    	
    	//再按条件进行分页查询
    	List<Document> listDocs=new ArrayList<Document>();
    	com.mongodb.client.FindIterable<Document> allDocs=MongoUtil.getCollection(client,dbName, tableName).find(filters); //按条件查询
    	Bson sortBson=new BasicDBObject("editTime", 1); //排序字段
    	MongoCursor<Document> cursor=allDocs.sort(sortBson).skip((pageNo - 1) * pageSize).limit(pageSize).iterator(); //分页查询
		while (cursor.hasNext()) {
            Document doc = cursor.next();
            listDocs.add(doc);
		}
		
		//构建返回数据
		IBasePageBean<Document> pageBean=(IBasePageBean<Document>)BeanFactory.getBean("PageBean");
		pageBean.setPageDocs(listDocs);
		pageBean.setTotal(totalRecords);
		
		return ViewUtil.getJsonView(pageBean);
		
	}
}
